<template>
  <div class="account-center-page">
    <div class="container">
      <div class="page-header">
        <h1>账户中心</h1>
      </div>

      <!-- 账户概览 -->
      <el-card class="account-overview">
        <div class="overview-content">
          <div class="account-balance">
            <div class="balance-item">
              <div class="balance-icon">
                <el-icon :size="32" color="#e6a23c">
                  <Wallet />
                </el-icon>
              </div>
              <div class="balance-info">
                <h3>余额</h3>
                <p class="balance-amount">¥{{ formatAmount(accountInfo.balance) }}</p>
                <div class="balance-actions">
                  <el-button size="small" type="primary" @click="showRechargeDialog = true">
                    充值
                  </el-button>
                  <el-button size="small" @click="showWithdrawDialog = true">
                    提现
                  </el-button>
                </div>
              </div>
            </div>

            <el-divider direction="vertical" />

            <div class="balance-item">
              <div class="balance-icon">
                <el-icon :size="32" color="#409eff">
                  <Star />
                </el-icon>
              </div>
              <div class="balance-info">
                <h3>积分</h3>
                <p class="balance-amount">{{ accountInfo.points }}</p>
                <div class="balance-actions">
                  <el-button size="small" @click="goToPointsExchange">
                    兑换
                  </el-button>
                  <el-button size="small" @click="goToPointsRecords">
                    明细
                  </el-button>
                </div>
              </div>
            </div>

            <el-divider direction="vertical" />

            <div class="balance-item">
              <div class="balance-icon">
                <el-icon :size="32" color="#67c23a">
                  <Ticket />
                </el-icon>
              </div>
              <div class="balance-info">
                <h3>优惠券</h3>
                <p class="balance-amount">{{ accountInfo.coupons }}</p>
                <div class="balance-actions">
                  <el-button size="small" @click="goToCoupons">
                    查看
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 快捷功能 -->
      <el-card class="quick-actions">
        <h3>快捷功能</h3>
        <div class="actions-grid">
          <div class="action-item" @click="goToBalanceRecords">
            <el-icon :size="24" color="#409eff"><List /></el-icon>
            <span>余额明细</span>
          </div>
          <div class="action-item" @click="goToPointsRecords">
            <el-icon :size="24" color="#409eff"><DataLine /></el-icon>
            <span>积分明细</span>
          </div>
          <div class="action-item" @click="goToCoupons">
            <el-icon :size="24" color="#67c23a"><Ticket /></el-icon>
            <span>我的优惠券</span>
          </div>
          <div class="action-item" @click="goToInvite">
            <el-icon :size="24" color="#e6a23c"><UserFilled /></el-icon>
            <span>邀请好友</span>
          </div>
          <div class="action-item" @click="goToBank">
            <el-icon :size="24" color="#f56c6c"><CreditCard /></el-icon>
            <span>银行卡</span>
          </div>
          <div class="action-item" @click="goToSecurity">
            <el-icon :size="24" color="#909399"><Lock /></el-icon>
            <span>安全设置</span>
          </div>
        </div>
      </el-card>

      <!-- 交易记录 -->
      <el-card class="recent-transactions">
        <div class="card-header">
          <h3>最近交易</h3>
          <el-button link @click="goToBalanceRecords">查看全部</el-button>
        </div>
        
        <div class="transactions-list" v-loading="transactionsLoading">
          <div
            v-for="transaction in recentTransactions"
            :key="transaction.id"
            class="transaction-item"
          >
            <div class="transaction-icon">
              <el-icon 
                :size="20" 
                :color="getTransactionColor(transaction.type)"
              >
                <component :is="getTransactionIcon(transaction.type)" />
              </el-icon>
            </div>
            <div class="transaction-content">
              <h4>{{ transaction.description }}</h4>
              <p class="transaction-time">{{ formatDate(transaction.createdAt) }}</p>
            </div>
            <div class="transaction-amount">
              <span 
                :class="[
                  'amount', 
                  transaction.type === 'income' ? 'income' : 'expense'
                ]"
              >
                {{ transaction.type === 'income' ? '+' : '-' }}¥{{ formatAmount(transaction.amount) }}
              </span>
            </div>
          </div>

          <div v-if="recentTransactions.length === 0" class="empty-transactions">
            <el-empty description="暂无交易记录" :image-size="100" />
          </div>
        </div>
      </el-card>

      <!-- 账户统计 -->
      <el-card class="account-stats">
        <h3>账户统计</h3>
        <div class="stats-grid">
          <div class="stat-item">
            <h4>本月消费</h4>
            <p class="stat-value">¥{{ formatAmount(accountStats.monthlySpent) }}</p>
          </div>
          <div class="stat-item">
            <h4>累计消费</h4>
            <p class="stat-value">¥{{ formatAmount(accountStats.totalSpent) }}</p>
          </div>
          <div class="stat-item">
            <h4>累计充值</h4>
            <p class="stat-value">¥{{ formatAmount(accountStats.totalRecharge) }}</p>
          </div>
          <div class="stat-item">
            <h4>累计积分</h4>
            <p class="stat-value">{{ accountStats.totalPoints }}</p>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 充值对话框 -->
    <el-dialog
      v-model="showRechargeDialog"
      title="账户充值"
      width="400px"
    >
      <el-form :model="rechargeForm" label-width="80px">
        <el-form-item label="充值金额">
          <el-input
            v-model="rechargeForm.amount"
            type="number"
            placeholder="请输入充值金额"
            :min="1"
            :max="10000"
          >
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="支付方式">
          <el-radio-group v-model="rechargeForm.paymentMethod">
            <el-radio label="alipay">支付宝</el-radio>
            <el-radio label="wechat">微信支付</el-radio>
            <el-radio label="bank">银行卡</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showRechargeDialog = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleRecharge"
            :loading="rechargeLoading"
          >
            立即充值
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 提现对话框 -->
    <el-dialog
      v-model="showWithdrawDialog"
      title="申请提现"
      width="400px"
    >
      <el-form :model="withdrawForm" label-width="80px">
        <el-form-item label="提现金额">
          <el-input
            v-model="withdrawForm.amount"
            type="number"
            placeholder="请输入提现金额"
            :min="1"
            :max="accountInfo.balance"
          >
            <template #append>元</template>
          </el-input>
          <div class="form-tip">
            可提现金额：¥{{ formatAmount(accountInfo.balance) }}
          </div>
        </el-form-item>
        <el-form-item label="提现账户">
          <el-select v-model="withdrawForm.bankCard" placeholder="请选择提现账户">
            <el-option
              v-for="card in bankCards"
              :key="card.id"
              :label="`${card.bankName} ****${card.cardNumber.slice(-4)}`"
              :value="card.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showWithdrawDialog = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleWithdraw"
            :loading="withdrawLoading"
          >
            申请提现
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Wallet,
  Star,
  Ticket,
  List,
  DataLine,
  UserFilled,
  CreditCard,
  Lock,
  Plus,
  Minus,
  RefreshRight
} from '@element-plus/icons-vue'
import { accountApi } from '@/services/api'
import dayjs from 'dayjs'

const router = useRouter()

// 数据定义
const accountInfo = ref({
  balance: 0,
  points: 0,
  coupons: 0
})

const accountStats = ref({
  monthlySpent: 0,
  totalSpent: 0,
  totalRecharge: 0,
  totalPoints: 0
})

const recentTransactions = ref([])
const transactionsLoading = ref(true)
const bankCards = ref([])

const showRechargeDialog = ref(false)
const showWithdrawDialog = ref(false)
const rechargeLoading = ref(false)
const withdrawLoading = ref(false)

const rechargeForm = reactive({
  amount: '',
  paymentMethod: 'alipay'
})

const withdrawForm = reactive({
  amount: '',
  bankCard: ''
})

// 生命周期
onMounted(() => {
  fetchAccountInfo()
  fetchAccountStats()
  fetchRecentTransactions()
  fetchBankCards()
})

// 方法定义
const fetchAccountInfo = async () => {
  try {
    const response = await accountApi.getAccountInfo()
    accountInfo.value = response.data
  } catch (error) {
    console.error('获取账户信息失败:', error)
    ElMessage.error('获取账户信息失败')
  }
}

const fetchAccountStats = async () => {
  try {
    const response = await accountApi.getAccountStats()
    accountStats.value = response.data
  } catch (error) {
    console.error('获取账户统计失败:', error)
  }
}

const fetchRecentTransactions = async () => {
  try {
    transactionsLoading.value = true
    const response = await accountApi.getTransactionList({ limit: 5 })
    recentTransactions.value = response.data.data
  } catch (error) {
    console.error('获取交易记录失败:', error)
  } finally {
    transactionsLoading.value = false
  }
}

const fetchBankCards = async () => {
  try {
    const response = await accountApi.getBankCards()
    bankCards.value = response.data
  } catch (error) {
    console.error('获取银行卡列表失败:', error)
  }
}

const handleRecharge = async () => {
  if (!rechargeForm.amount || rechargeForm.amount <= 0) {
    ElMessage.warning('请输入有效的充值金额')
    return
  }

  try {
    rechargeLoading.value = true
    const response = await accountApi.recharge({
      amount: parseFloat(rechargeForm.amount),
      paymentMethod: rechargeForm.paymentMethod
    })
    
    // 跳转到支付页面
    window.open(response.data.paymentUrl, '_blank')
    showRechargeDialog.value = false
    ElMessage.success('充值订单已创建，请完成支付')
  } catch (error) {
    console.error('创建充值订单失败:', error)
    ElMessage.error('充值失败')
  } finally {
    rechargeLoading.value = false
  }
}

const handleWithdraw = async () => {
  if (!withdrawForm.amount || withdrawForm.amount <= 0) {
    ElMessage.warning('请输入有效的提现金额')
    return
  }

  if (!withdrawForm.bankCard) {
    ElMessage.warning('请选择提现账户')
    return
  }

  try {
    withdrawLoading.value = true
    await accountApi.withdraw({
      amount: parseFloat(withdrawForm.amount),
      bankCardId: withdrawForm.bankCard
    })
    
    showWithdrawDialog.value = false
    ElMessage.success('提现申请已提交，预计1-3个工作日到账')
    fetchAccountInfo()
  } catch (error) {
    console.error('申请提现失败:', error)
    ElMessage.error('提现申请失败')
  } finally {
    withdrawLoading.value = false
  }
}

const goToBalanceRecords = () => {
  router.push('/account/balance')
}

const goToPointsRecords = () => {
  router.push('/account/points')
}

const goToCoupons = () => {
  router.push('/coupons')
}

const goToPointsExchange = () => {
  router.push('/points/exchange')
}

const goToInvite = () => {
  router.push('/invite')
}

const goToBank = () => {
  router.push('/bank-cards')
}

const goToSecurity = () => {
  router.push('/security')
}

const getTransactionIcon = (type) => {
  const iconMap = {
    income: Plus,
    expense: Minus,
    refund: RefreshRight
  }
  return iconMap[type] || Plus
}

const getTransactionColor = (type) => {
  const colorMap = {
    income: '#67c23a',
    expense: '#f56c6c',
    refund: '#409eff'
  }
  return colorMap[type] || '#909399'
}

const formatAmount = (amount) => {
  return parseFloat(amount || 0).toFixed(2)
}

const formatDate = (date) => {
  return dayjs(date).format('MM-DD HH:mm')
}
</script>

<style lang="scss" scoped>
.account-center-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  margin-bottom: 24px;

  h1 {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    color: #333;
  }
}

.el-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.account-overview {
  .overview-content {
    padding: 20px 0;
  }

  .account-balance {
    display: flex;
    justify-content: space-around;
    align-items: center;

    .balance-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      text-align: center;
      flex: 1;

      .balance-icon {
        margin-bottom: 12px;
      }

      .balance-info {
        h3 {
          margin: 0 0 8px 0;
          font-size: 16px;
          color: #666;
        }

        .balance-amount {
          margin: 0 0 16px 0;
          font-size: 24px;
          font-weight: 600;
          color: #333;
        }

        .balance-actions {
          display: flex;
          gap: 8px;
          justify-content: center;
        }
      }
    }
  }
}

.quick-actions {
  h3 {
    margin: 0 0 20px 0;
    font-size: 18px;
    font-weight: 600;
  }

  .actions-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 16px;

    .action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20px;
      background-color: #f8f9fa;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        background-color: #e9ecef;
        transform: translateY(-2px);
      }

      .el-icon {
        margin-bottom: 8px;
      }

      span {
        font-size: 14px;
        color: #333;
      }
    }
  }
}

.recent-transactions {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }
  }

  .transactions-list {
    .transaction-item {
      display: flex;
      align-items: center;
      padding: 16px 0;
      border-bottom: 1px solid #f0f2f5;

      &:last-child {
        border-bottom: none;
      }

      .transaction-icon {
        margin-right: 16px;
        width: 40px;
        height: 40px;
        border-radius: 20px;
        background-color: #f5f7fa;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .transaction-content {
        flex: 1;

        h4 {
          margin: 0 0 4px 0;
          font-size: 14px;
          font-weight: 500;
          color: #333;
        }

        .transaction-time {
          margin: 0;
          font-size: 12px;
          color: #999;
        }
      }

      .transaction-amount {
        .amount {
          font-size: 16px;
          font-weight: 600;

          &.income {
            color: #67c23a;
          }

          &.expense {
            color: #f56c6c;
          }
        }
      }
    }

    .empty-transactions {
      padding: 40px 0;
      text-align: center;
    }
  }
}

.account-stats {
  h3 {
    margin: 0 0 20px 0;
    font-size: 18px;
    font-weight: 600;
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;

    .stat-item {
      text-align: center;
      padding: 20px;
      background-color: #f8f9fa;
      border-radius: 8px;

      h4 {
        margin: 0 0 8px 0;
        font-size: 14px;
        color: #666;
      }

      .stat-value {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: #333;
      }
    }
  }
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .account-overview {
    .account-balance {
      flex-direction: column;
      gap: 24px;

      .el-divider {
        display: none;
      }

      .balance-item {
        width: 100%;
      }
    }
  }

  .actions-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .transaction-item {
    .transaction-content {
      h4 {
        font-size: 13px;
      }
    }

    .transaction-amount {
      .amount {
        font-size: 14px;
      }
    }
  }
}
</style> 